package com.mf.service.impl;

import com.mf.entity.GoodsMold;
import com.mf.repository.GoodsMoldReponsitory;
import com.mf.service.GoodsMoldService;
import com.mf.util.StringUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Service("goodsMoldService")
public class GoodsMoldServiceImpl implements GoodsMoldService {

    @Resource
    private GoodsMoldReponsitory goodsMoldReponsitory;

    @Override
    public List<GoodsMold> list(GoodsMold goodsMold, Integer page, Integer pageSize, Sort.Direction direction, String... properties){
        Pageable pageable = new PageRequest(page - 1, pageSize);

        Page<GoodsMold> goodsMoldPage = goodsMoldReponsitory.findAll(new Specification<GoodsMold>() {
            @Override
            public Predicate toPredicate(Root<GoodsMold> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                if(goodsMold != null){
                    if (StringUtil.isNotEmpty(goodsMold.getName())) {
                        predicate.getExpressions().add(criteriaBuilder.like(root.get("name"), "%" + goodsMold.getName() + "%"));
                    }
                }
                return predicate;
            }
        },pageable);

        return  goodsMoldPage.getContent();

    }

    @Override
    public Long getCount(GoodsMold goodsMold){
        Long count = goodsMoldReponsitory.count(new Specification<GoodsMold>() {
            @Override
            public Predicate toPredicate(Root<GoodsMold> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                if(goodsMold != null){
                    if(StringUtil.isNotEmpty(goodsMold.getName())){
                        predicate.getExpressions().add(criteriaBuilder.like(root.get("name"), "%" + goodsMold.getName() + "%"));
                    }
                }
                return predicate;
            }
        });
        return count;
    }

    @Override
    public void save(GoodsMold goodsMold){
        goodsMoldReponsitory.save(goodsMold);
    }


    @Override
    public void delete(Integer id){
        goodsMoldReponsitory.delete(id);
    }

    @Override
    public List<GoodsMold> all() {
        return goodsMoldReponsitory.findAll();
    }

}
